package com.qf.openapi.web.master.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.openapi.web.master.vo.MessageVo;
import lombok.SneakyThrows;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * @author 王权富贵
 */
public class MyExResolver implements HandlerExceptionResolver {

    @SneakyThrows
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ex.printStackTrace();
        ModelAndView mv = new ModelAndView();
        if (ex instanceof SQLException) {
            mv.setViewName("redirect:/error/error1.html");
        } else if (ex instanceof NullPointerException) {
            mv.setViewName("redirect:/error/error2.html");
        } else {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            PrintWriter writer = response.getWriter();
            String json = objectMapper.writeValueAsString(new MessageVo("0",false,"其他错误",null));
            writer.write(json);
        }
        return mv;
    }
}
